const express = require('express');
const router = express.Router();
const Brand = require('../models/brand');
const mongoose = require('mongoose');

// 获取品牌列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, categoryId, name, status } = req.query;
    const query = {};

    if (categoryId) query.categoryId = categoryId;
    if (name) query.name = new RegExp(name, 'i');
    if (status !== undefined) query.status = status === 'true';

    const total = await Brand.countDocuments(query);
    const list = await Brand.find(query)
      .populate('category')
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: 1, createdAt: -1 });

    res.status(200).json({
      code: 200,
      data: {
        list,
        total,
        page: Number(page),
        pageSize: Number(pageSize)
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取品牌列表失败',
      error: error.message
    });
  }
});

// 获取品牌详情
router.get('/detail', async (req, res) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(400).json({
        code:500,
        message: '品牌ID不能为空'
      });
    }

    const brand = await Brand.findOne({ id });
    if (!brand) {
      return res.status(404).json({
        code:500,
        message: '品牌不存在'
      });
    }

    res.json({
      success: true,
      data: brand
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: '获取品牌详情失败'
    });
  }
});

// 创建品牌
router.post('/create', async (req, res) => {
  try {
    // 生成唯一ID
    const timestamp = new Date().getTime();
    const random = Math.floor(Math.random() * 1000);
    const id = `${timestamp}${random}`;

    // 创建新品牌，添加 id 字段
    const brand = new Brand({
      ...req.body,
      id
    });
    
    await brand.save();

    res.status(200).json({
      code: 200,
      data: brand,
      message: '创建成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '创建品牌失败',
      error: error.message
    });
  }
});

// 更新品牌
router.post('/update', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    const brand = await Brand.findOneAndUpdate(
      { id },
      updateData,
      { new: true }
    );

    if (!brand) {
      return res.status(404).json({
        code: 500,
        message: '品牌不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: brand,
      message: '更新成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '更新品牌失败',
      error: error.message
    });
  }
});

// 删除品牌
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;
    const brand = await Brand.findOneAndDelete({ id });

    if (!brand) {
      return res.status(404).json({
        code: 500,
        message: '品牌不存在'
      });
    }

    res.status(200).json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '删除品牌失败',
      error: error.message
    });
  }
});

module.exports = router; 